import {Tree, Row, Col} from 'antd';
// import Tree from '../../_antd1.11.2/Tree'
// import Row from '../../_antd1.11.2/Row'
// import Col from '../../_antd1.11.2/Col'

const TreeNode = Tree.TreeNode;
import WeaInputSearch from '../wea-input-search'
import WeaScroll from '../wea-scroll';
import cloneDeep from 'lodash/cloneDeep'
import isEqual from 'lodash/isEqual';

const isArray = (datas) => {
    return datas && datas.length>0;
}
class WeaLeftTree extends React.Component {
     constructor(props) {
        super(props);
        let keysArr = [];
        isArray(props.datas) && props.datas.map(data=>{
   			keysArr.push(data.domid);
	    })
        this.state = {
            height:0,
            datasShow: props.datas || [],
            expandedKeys: keysArr,
            selectedKeys: props.selectedKeys || [],
        }
    }
    scrollheigth(){
    	let top = jQuery(".wea-new-tree .wea-new-tree-scroll").offset() ? (jQuery(".wea-new-tree .wea-new-tree-scroll").offset().top ? jQuery(".wea-new-tree .wea-new-tree-scroll").offset().top : 0) : 0;
        let scrollheigth = document.documentElement.clientHeight - top - 15;
        jQuery(".wea-new-tree .wea-new-tree-scroll").height(scrollheigth);
    }
    componentDidMount(){
        this.scrollheigth();
        jQuery(window).resize(() => {
		    this._reactInternalInstance !== undefined && this.scrollheigth()
		});
//      this.resetSearchBoxWidth();
//      const {datasShow} = this.state;
//  	let keysArr = [];
//  	isArray(datasShow) && datasShow.map(data=>{
// 			keysArr.push(data.domid);
//	    })
//  	this.setState({expandedKeys:keysArr})
    }
    shouldComponentUpdate(nextProps,nextState){
//  	console.log((!isEqual(this.state.selectedKeys,nextState.selectedKeys) ||
//      !isEqual(this.props.selectedKeys,nextProps.selectedKeys) ||
//      !isEqual(this.props.datas,nextProps.datas) ||
//      !isEqual(this.props.counts,nextProps.counts) ||
//      !isEqual(this.props.countsType,nextProps.countsType) ||
//      this.props.loading !== nextProps.loading ||
//      !isEqual(this.state.expandedKeys,nextState.expandedKeys) ||
//      !isEqual(this.state.datasShow,nextState.datasShow) ||
//      this.state.height !== nextState.height), this.props,nextProps,this.state,nextState);

        return !isEqual(this.state.selectedKeys,nextState.selectedKeys) ||
        !isEqual(this.props.selectedKeys,nextProps.selectedKeys) ||
        !isEqual(this.props.datas,nextProps.datas) ||
        !isEqual(this.props.counts,nextProps.counts) ||
        !isEqual(this.props.countsType,nextProps.countsType) ||
        this.props.loading !== nextProps.loading ||
        !isEqual(this.state.expandedKeys,nextState.expandedKeys) ||
        !isEqual(this.state.datasShow,nextState.datasShow) ||
        this.state.height !== nextState.height
    }
    componentDidUpdate(prevProps,prevState){
        this.scrollheigth();
    }
    componentWillReceiveProps(nextProps){
        const {datas, selectedKeys} = this.props;
        if(!isEqual(datas,nextProps.datas)){
        	let keysArr = [];
	    	isArray(nextProps.datas) && nextProps.datas.map(data=>{
	   			keysArr.push(data.domid);
		    })
        	this.setState({datasShow: nextProps.datas,expandedKeys:keysArr})
        }
        if(!isEqual(selectedKeys,nextProps.selectedKeys) && !isEqual(this.state.selectedKeys,nextProps.selectedKeys)){
        	this.setState({selectedKeys: nextProps.selectedKeys})
        }
    }
    render() {
        const {datas,counts,countsType,loading} = this.props;
        const {datasShow,expandedKeys,selectedKeys} = this.state;
        //console.log('left tree render')
        //console.log("datas autoExpandParent:",datas);
        //expandedKeys={this.getRootKeys(datas)}
        //console.log("!isArray(datas)：",!isArray(datas));
        //if(!isArray(datas)) {
        //    return <div></div>
        //}
        //console.log("is in :",datas);
        //console.log("counts:",counts);
        //重置全部展开
//      alert(!!counts +" "+ (JSON.stringify(counts) == '{}') +" "+ !isArray(datasShow));
        return (
           <div className="wea-new-tree">
               <div className="wea-input-wraper">
                   <span onClick={this.onFliterAll.bind(this,'')} style={{"cursor":"pointer"}}><b>全部类型</b></span>
                   <WeaInputSearch onSearchChange={this.onSearchChange.bind(this)}/>
               </div>
               <WeaScroll className="wea-new-tree-scroll" typeClass="scrollbar-macosx">
                    {isArray(datasShow) ? <Tree openTransitionName='' showLine defaultExpandAll expandedKeys={expandedKeys} onExpand={this.onExpandChange.bind(this)} onSelect={this.onSelect.bind(this)} selectedKeys={selectedKeys}>
                        {this.renderTreeNodes(datasShow,counts,countsType,0)}
                    </Tree> : ''}
               </WeaScroll>
           </div>
        ) //defaultExpandedKeys={this.getRootKeys(datas)}
    }
    onExpandChange(expandedKeys, nodeObj){
		const {datasShow} = this.state;
		this.setState({expandedKeys:expandedKeys})
    }
    titileNumClick(keys,countsType,e){
    	this.onSelect(keys,countsType);
    	//暂时未测出哪个管用。。
    	e.stopPropagation && e.stopPropagation();
    	e.preventDefault && e.preventDefault();
    	e.nativeEvent && e.nativeEvent.preventDefault();
    }
    onSelect(keys,countsType) {
        const {counts} = this.props;
        const key = keys && keys.length>0?keys[0]:"";
        this.setState({selectedKeys: keys});
        if (typeof (this.props.onSelect) == "function") {
            //console.log("counts:",counts[key]);
            key && key.length !== 0 && this.props.onSelect(key,counts ? counts[key] : '',countsType ? countsType : '');
        }
    }
    onFliterAll() {
    	if(typeof this.props.onFliterAll == 'function'){
    		this.props.onFliterAll();
    	}
    }
    onSearchChange(v){
        const {datas} = this.props;
            let leftTreeShow = [];
            datas.map(t=>{
            	let newT = cloneDeep(t);
            	if(newT.childs && newT.childs.length > 0) newT.childs = newT.childs.filter(c=>{return c.name.indexOf(v) >= 0})
            	if(newT.childs && newT.childs.length > 0) leftTreeShow.push(newT);
            });
    	this.setState({datasShow:leftTreeShow})
    }
    renderTreeNodes(datas,counts,countsType,lev) {
//        console.log("datas",datas,"counts",counts,"countsType",countsType);
        let that = this;
        let newDatas = [];
        datas && datas.map((data)=>{
	        if(!counts || (counts && JSON.stringify(counts) == '{}')){
	        	newDatas.push(
	        		<TreeNode browserTree={true} key={data.domid} title={that.getTitle(data,counts,countsType)} level={lev}>
                		{isArray(data.childs) && that.renderTreeNodes(data.childs,counts,countsType,lev+1)}
                	</TreeNode>
                )
	        }else{
//	        	let flowAllNum = (counts && counts[data.domid]) ? (counts[data.domid].flowAll ? counts[data.domid].flowAll : ''):'';
				//流程
	        	if(counts && counts[data.domid] && counts[data.domid].flowAll && counts[data.domid].flowAll !== '0'){
		        	newDatas.push(
		        		<TreeNode browserTree={true} title={that.getTitle(data,counts,countsType)} key={data.domid} level={lev}>
	                		{isArray(data.childs) && that.renderTreeNodes(data.childs,counts,countsType,lev+1)}
	                	</TreeNode>
	                )
	        	}else if(counts && counts[data.domid] && typeof counts[data.domid].allNum !== 'undefined'){//知识，这需求设计真是坑了
		        	newDatas.push(
		        		<TreeNode browserTree={true} {...data} title={that.getTitle(data,counts,countsType)} id={data.key} key={data.domid} level={lev}>
	                		{isArray(data.childs) && that.renderTreeNodes(data.childs,counts,countsType,lev+1)}
	                	</TreeNode>
	                )
		        }
	        }
        });
        return newDatas;
    }
    getTitle(data,counts,countsType) {
        let _this = this;
        let flowSpan = [];
        let countsTypeShow = [];
        let notShowEm = 0;
        let keys = [data.domid];
    	countsType && countsType.map((c,i)=>{
            let num = (counts && counts[data.domid]) ? (counts[data.domid][c.name] ? counts[data.domid][c.name] : ''):'';
    		if(num && num !== '0'){
    			notShowEm ++;
    			countsTypeShow.push(c);
    			if(notShowEm !== 1) {
                    flowSpan.push(<em
                    className={c.isshow ? '' : 'wf-isshow'}
                    style={{"display":c.isshow ? "inline" : "none"}}> / </em>)
                }
                flowSpan.push(
	                <span title={c.title} className={c.isshow ? '' : 'wf-isshow'} style={{"color":c.color,"display":c.isshow ? "inline-block" : "none"}} onClick={this.titileNumClick.bind(this,keys,c)}>{num}</span>
	    		);
    		}
    	});
        return (
            <Row onMouseEnter={this.titleHoverIn.bind(this,countsTypeShow)} onMouseLeave={this.titleHoverOut.bind(this,countsTypeShow)}>
                <Col span="16" className="titleText" title={data.name}>
                {data.name}
                </Col>
                <Col span="8" className="titleNum"  >
	                <div>
	                	{flowSpan}
	                </div>
                </Col>
            </Row>
        )
    }
    getRootKeys(datas) {
        let keyArr = [];
        datas.map((data)=>{
            keyArr.push(data.domid);
        });
        return keyArr;
    }
    titleHoverIn(countsTypeShow,e){
        jQuery(e.target).closest(".wea-tree-wrap").find(".ant-tree-title .titleNum").each((index,item)=>{
        	jQuery(item).find(".wf-isshow").css({'display':'inline-block'});
            jQuery(item).find("span").each((i,m)=>{
                jQuery(m).css({"background-color":countsTypeShow[i].color,"color":"#fff"});
            })
        })
    }
	titleHoverOut(countsTypeShow,e){
    	jQuery(e.target).closest(".wea-tree-wrap").find(".ant-tree-title .titleNum").each((index,item)=>{
    		jQuery(item).find(".wf-isshow").css({'display':'none'});
            jQuery(item).find("span").each((i,m)=>{
                jQuery(m).css({"color":countsTypeShow[i].color,"background-color":"transparent"});
            })
        })
    }
//  resetSearchBoxWidth() {
//      let totalWidth = $(".wea-new-tree .wea-input-wraper").width();
//      let leftWidth = $($(".wea-new-tree .wea-input-wraper span")[0]).width();
//      let searchBoxWidth = totalWidth - leftWidth - 40;
//      let searchBox = $(".wea-new-tree .wea-input-wraper .wea-input-focus");
//      searchBox.show();
//      // 搜索框的宽度不够的情况下隐藏
//      if (searchBoxWidth < 35) {
//          searchBox.hide();
//      } else {
//          searchBox.width(searchBoxWidth);
//      }
//  }

}


export default WeaLeftTree;